//
//  ViewController.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 15/4/2.
//  Copyright (c) 2015年 Minus. All rights reserved.
//

#import "ViewController.h"
#import "MDXPGApplianceApi.h"
#import "FactoryDataBody.h"
#import "MDUserDefaults.h"

#import "DeviceStatus.h"
#import "FactoryDataBody.h"

#import "TemperatureUtil.h"

@interface ViewController ()
{
    MDXPGApplianceApi *_api;
}

@property (weak, nonatomic) IBOutlet UITextField *textFieldEmail;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPassword;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPasswordNew;

@property (weak, nonatomic) IBOutlet UILabel *labelTips;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *barButtonDevice;
@property (weak, nonatomic) IBOutlet UIButton *buttonGetHomeList;
@property (weak, nonatomic) IBOutlet UIButton *buttonCreateHome;
@property (weak, nonatomic) IBOutlet UIButton *buttonChangePwd;
@property (weak, nonatomic) IBOutlet UIButton *buttonResetPwd;
@property (weak, nonatomic) IBOutlet UIButton *buttonCheckEmail;
@property (weak, nonatomic) IBOutlet UIButton *buttonRegister;
@property (weak, nonatomic) IBOutlet UIButton *buttonLogin;


@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    _api = [MDXPGApplianceApi getInstance];
    
//    [self createCommand];
    
    self.textFieldEmail.text = @"44@qq.com";
    self.textFieldPassword.text = @"123456";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.barButtonDevice.enabled = NO;
    self.buttonGetHomeList.enabled = NO;
    self.buttonCreateHome.enabled = NO;
    self.buttonChangePwd.enabled = NO;
    
    self.buttonLogin.enabled = YES;
    self.buttonResetPwd.enabled = YES;
    self.buttonCheckEmail.enabled = YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - Http request operations

// 检测邮箱可用性
- (IBAction)actionCheckEmailAvailability:(id)sender
{
    NSString *email = self.textFieldEmail.text;
    
    if (email == nil || [email length] <= 0)
    {
        self.labelTips.text = @"邮箱不能为空";
        return;
    }
    
    self.labelTips.text = @"正在检测邮箱可用性...";
    
    [[MDXPGApplianceApi getInstance] checkEmailAvailability:email completion:^(BaseMessage *baseMessage, int emailStatus) {
        
        if ([baseMessage getCode] == 0) // 成功
        {
            // TODO: handle emailStatus ...
            
            NSString *statusString;
            
            switch (emailStatus)
            {
                case 0:
                    statusString = @"未注册";
                    break;
                    
                case 1:
                    statusString = @"已注册未激活";
                    break;
                    
                case 2:
                    statusString = @"已注册已激活";
                    break;
                    
                case 3:
                    statusString = @"已注册禁用";
                    break;
                    
                default:
                    statusString = @"";
                    break;
            }
            
            self.labelTips.text = [NSString stringWithFormat:@"邮箱: %@ %@", email, statusString];
        }
        else
        {
            NSLog(@"error code: %@", @([baseMessage getCode]));
            NSLog(@"error message: %@", [baseMessage getMessage]);
            self.labelTips.text = [baseMessage getMessage];
        }
    }];
}

// 用户注册
- (IBAction)actionRegister:(id)sender
{
    NSString *email = self.textFieldEmail.text;
    NSString *password = self.textFieldPassword.text;
    
    if ([email length] <= 0)
    {
        self.labelTips.text = @"邮箱不能为空";
        return;
    }
    
    if ([password length] <= 0)
    {
        self.labelTips.text = @"密码不能为空";
        return;
    }
    
    self.labelTips.text = @"正在注册账号...";
    
    [[MDXPGApplianceApi getInstance] userRegister:email password:password completion:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0) // 成功
        {
            self.labelTips.text = @"注册成功";
        }
        else
        {
            self.labelTips.text = [NSString stringWithFormat:@"注册失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

- (IBAction)actionLogin:(id)sender
{
//    [self performSegueWithIdentifier:@"loginSuccessSegue" sender:nil];
//    return;
    
    NSString *email = self.textFieldEmail.text;
    NSString *password = self.textFieldPassword.text;
    
    if ([email length] <= 0)
    {
        self.labelTips.text = @"邮箱不能为空";
        return;
    }
    
    if ([password length] <= 0)
    {
        self.labelTips.text = @"密码不能为空";
        return;
    }
    
    self.labelTips.text = @"正在获取loginID...";
    
    // 登录之前，先获取loginID
    [[MDXPGApplianceApi getInstance] getLoginID:email completion:^(BaseMessage *baseMessage, NSString *loginID) {
        
        if ([baseMessage getCode] == 0) // 成功获取loginID
        {
            self.labelTips.text = @"成功获取loginID，正在登录...";
            
            // 获取loginID后，再进行登录
            [self userLogin:email password:password loginID:loginID];
        }
        else    // 失败
        {
            NSLog(@"error code: %@", @([baseMessage getCode]));
            NSLog(@"error message: %@", [baseMessage getMessage]);
            
            self.labelTips.text = [NSString stringWithFormat:@"获取loginID失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 获取家庭列表
- (IBAction)actionGetHomeList:(id)sender
{
    self.labelTips.text = @"正在获取家庭列表...";
    
    [[MDXPGApplianceApi getInstance] getHomeList:^(BaseMessage *baseMessage, NSArray *familyInfos) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelTips.text = @"获取家庭列表成功";
            
            if ([familyInfos count] > 0)
            {
                for (FamilyInfo *info in familyInfos)
                {
                    NSLog(@"family id: %@", [info getId]);
                    NSLog(@"family number: %@", [info getNumber]);
                    NSLog(@"%@", [info description]);
                }
                
                FamilyInfo *info = [familyInfos firstObject];
                
                self.labelTips.text = [self.labelTips.text stringByAppendingFormat:@", 已有家庭，家庭名：%@。", [info getName]];
                
                self.buttonCreateHome.enabled = NO;
                self.barButtonDevice.enabled = YES;
            }
            else    // 没有家庭，创建一个
            {
                self.labelTips.text = [self.labelTips.text stringByAppendingString:@", 没有家庭，请创建一个。"];
                
                self.buttonCreateHome.enabled = YES;
                self.barButtonDevice.enabled = NO;
            }
        }
        else
        {
            self.labelTips.text = [NSString stringWithFormat:@"获取家庭列表失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 创建家庭
- (IBAction)actionCreateHome:(id)sender
{
    NSString *name = @"2501";
    NSString *description = @"这是一栋大厦";
    NSString *address = @"先烈中路102号华盛大厦2501杰升科技";
    
    self.labelTips.text = @"正在创建家庭...";
    
    [[MDXPGApplianceApi getInstance] createFamily:name
                                      description:description
                                          address:address completion:^(BaseMessage *baseMessage, Family *family) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelTips.text = @"创建家庭成功";
            
            NSLog(@"family id: %@", [family getId]);
            NSLog(@"family number: %@", [family getNumber]);
            
            self.barButtonDevice.enabled = YES;
            self.buttonCreateHome.enabled = NO;
        }
        else
        {
            self.labelTips.text = [NSString stringWithFormat:@"创建家庭失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 修改密码
- (IBAction)actionChangePassword:(id)sender
{
    NSString *oldPassword = self.textFieldPassword.text;
    NSString *newPassword = self.textFieldPasswordNew.text;
    
    if ([oldPassword length] <= 0 || [newPassword length] <= 0)
    {
        self.labelTips.text = @"密码不能为空";
        return;
    }
    
    self.labelTips.text = @"正在修改密码...";
    
    [[MDXPGApplianceApi getInstance] updatePassword:oldPassword
                                        newPassword:newPassword completion:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelTips.text = @"修改密码成功";
        }
        else
        {
            self.labelTips.text = [NSString stringWithFormat:@"修改密码失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 重置密码
- (IBAction)actionResetPassword:(id)sender
{
    NSString *email = self.textFieldEmail.text;
    
    if ([email length] <= 0)
    {
        self.labelTips.text = @"邮箱不能为空";
        return;
    }
    
    self.labelTips.text = @"正在重置密码...";
    
    [[MDXPGApplianceApi getInstance] forgetPassword:email completion:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelTips.text = @"重置密码成功，请登录邮箱更改密码";
        }
        else
        {
            self.labelTips.text = [NSString stringWithFormat:@"重置密码失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}


// 用户登录
- (void)userLogin:(NSString *)email password:(NSString *)password loginID:(NSString *)loginID
{
    [[MDXPGApplianceApi getInstance] userLogin:email
                                      password:password
                                       loginID:loginID completion:^(BaseMessage *baseMessage, User *user) {
        
        if ([baseMessage getCode] == 0) // 成功登录
        {
            NSLog(@"sessionID: %@", [user getSessionId]);
            NSLog(@"userID: %@", [user getUserId]);
            NSLog(@"nickNmae: %@", [user getNickname]);
            NSLog(@"accessToken: %@", [user getAccessToken]);
            
            self.labelTips.text = @"登录成功";
            
            self.buttonGetHomeList.enabled = YES;
            self.buttonChangePwd.enabled = YES;
            self.buttonCheckEmail.enabled = NO;
            self.buttonResetPwd.enabled = NO;
            self.buttonLogin.enabled = NO;
        }
        else    //  登录失败
        {
            NSLog(@"error code: %@", @([baseMessage getCode]));
            NSLog(@"error message: %@", [baseMessage getMessage]);
            
            self.labelTips.text = [NSString stringWithFormat:@"登录失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

- (IBAction)actionGetUserInfo:(id)sender
{
    [[MDXPGApplianceApi getInstance] getUserInfo:^(BaseMessage *baseMessage, UserInfo *userInfo) {
        
        if ([baseMessage getCode] == 0) // 成功上传
        {
            self.labelTips.text = [NSString stringWithFormat:@"获取用户信息成功"];
            
            NSLog(@"user infomation: %@", [userInfo description]);
            
            /**
             *  UserInfo 各个成员变量只能通过 get/set 方法读取和设置值
             *  详细说明请参照 readme.html
             */
        }
        else    //  上传失败
        {
            NSLog(@"error code: %@", @([baseMessage getCode]));
            NSLog(@"error message: %@", [baseMessage getMessage]);
            
            self.labelTips.text = [NSString stringWithFormat:@"获取用户信息失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}


// 上传头像
- (IBAction)actionUploadUserIcon:(id)sender
{
    UIImage *image = [UIImage imageNamed:@"usericon"];
    
    self.labelTips.text = @"正在上传头像...";
    
    [[MDXPGApplianceApi getInstance] userIcon:image completion:^(BaseMessage *baseMessage, NSString *urlString) {
        
        if ([baseMessage getCode] == 0) // 成功上传
        {
            NSLog(@"profile image url: %@", urlString);
            self.labelTips.text = [NSString stringWithFormat:@"头像上传成功 %@", urlString];
        }
        else    //  上传失败
        {
            NSLog(@"error code: %@", @([baseMessage getCode]));
            NSLog(@"error message: %@", [baseMessage getMessage]);
            
            self.labelTips.text = [NSString stringWithFormat:@"上传头像失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 重复激活邮件
- (IBAction)actionResendActivatedMail:(id)sender
{
    self.labelTips.text = @"正在发送激活邮件...";
    
    NSString *email = self.textFieldEmail.text;
    
    [[MDXPGApplianceApi getInstance] sendActivateEmail:email completion:^(BaseMessage *baseMessage) {
        
        self.labelTips.text = @"";
        
        NSLog(@"error code: %@", @([baseMessage getCode]));
        NSLog(@"error message: %@", [baseMessage getMessage]);
    }];
}


#pragma mark - 设备操作
- (IBAction)actionPushtoDevicePage:(id)sender
{
    [self performSegueWithIdentifier:@"loginSuccessSegue" sender:nil];
}

@end
